package com.csii.security;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.csii.user.entity.SysUser;
import com.csii.user.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 通过手机号获取用户信息和权限资源
 * @Auther: ian
 */
@Component("dingTalkUserDetailsService") // 一定不要少了
public class DingTalkUserDetailsService extends AbstractUserDetailsService {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    ISysUserService sysUserService;

    @Override
    public SysUser findSysUser(String usernameOrMobile) {
        JSONObject jsb=JSONObject.parseObject(HttpUtil.get("http://vp.csiicloud.com:8001/user/author?dd_token="+usernameOrMobile));
        JSONObject userJson=jsb.getJSONObject("data");
        if(userJson!=null)
        {
            String openId=userJson.getString("id");
            SysUser user= sysUserService.selectOnByThirdId("DingTalk",openId);
            if(user==null) {
                user = new SysUser();
                user.setUsername(userJson.getString("ztId"));
                user.setRealname(userJson.getString("name"));
                user.setAvatar(userJson.getString("avatar"));
                user.setCreateTime(new Date());
                user.setEmail(userJson.getString("email"));
                user.setStatus(1);
                user.setPhone(userJson.getString("mobile"));
                user.setPassword(new BCryptPasswordEncoder().encode(RandomUtil.randomString(6)));
                user.setThirdId(openId);
                user.setThirdType("DingTalk");
                sysUserService.save(user);
            }
            return user;
        }
        return null;
    }

}